<template>
  <div class="img-text" id="img-text">
    <el-form
      label-position="top"
      :model="objData"
      ref="dialogPointForm"
      label-width="150px"
      class="demo-dynamic"
      v-if="name!=='scenic'"
    >
      <el-form-item
        :rules="rules.title"
        prop="title"
        label="游玩标题"
        v-if="mainOption.tiOption.title===''||mainOption.tiOption.title?true:false"
      >
        <el-input
          size="mini"
          v-model="objData.title"
          :maxlength="objData.pointTitleMax"
          show-word-limit
          :disabled="mainOption.operate==='show'?true:false"
        ></el-input>
      </el-form-item>
      <el-form-item
        :rules="rules.playTime"
        prop="play_time"
        label="游玩时长(小时单位)"
        v-if="mainOption.tiOption.play_time?true:false"
      >
        <el-input-number
          size="mini"
          v-model="objData.play_time"
          :precision="1"
          :step="0.1"
          :min="1"
          :disabled="mainOption.operate==='show'?true:false"
        ></el-input-number>
      </el-form-item>
    </el-form>
    <div class="content">
      <draggable
        v-model="scenicDataComp"
        :options="{group:'people'}"
        v-if="name==='scenic'"
        @change="change"
      >
        <div
          v-for="(stepCon, stepConIndex) in scenicDataComp"
          :key="stepConIndex"
          style="margin: 20px 0;"
        >
          <div
            v-if="stepCon.type === 'text'"
            style="border:1px dotted #cccccc;border-radius: 4px;margin: 5px;position: relative;"
          >
            <div
              style="line-height: 2;padding-left: 5px"
              @click="pointTextClick(stepCon.val, stepConIndex)"
              v-html="replaceN(stepCon.val)"
            >
            </div>
            <el-popover
              trigger="click"
              placement="top"
              width="160"
              v-model="stepCon.IsDel"
              v-show="mainOption.operate === 'show'?false:true"
            >
              <p>确定删除内容吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="stepCon.IsDel = false">取消</el-button>
                <el-button type="primary" size="mini" @click="stepConDel(stepConIndex)">确定</el-button>
              </div>
              <span
                class="el-icon-error"
                slot="reference"
                style="position: absolute;top:0;right:0;color: salmon;font-size: 20px;transform: translateX(40%) translateY(-40%)"
              ></span>
            </el-popover>
          </div>
          <div v-else style="position: relative">
            <!-- <el-image :src="'http://'+stepCon.imgList.url"></el-image> -->
            <el-image
              :src="stepCon.imgList.url"
              @click="pointIMgClick(stepCon.imgList.url, stepConIndex)"
            ></el-image>
            <el-popover
              placement="top"
              width="160"
              v-model="stepCon.IsDel"
              v-show="mainOption.operate === 'show'?false:true"
            >
              <p>确定删除内容吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="stepCon.IsDel = false">取消</el-button>
                <el-button type="primary" size="mini" @click="stepConDel(stepConIndex)">确定</el-button>
              </div>
              <span
                class="el-icon-error"
                slot="reference"
                style="position: absolute;top:0;right:0;color: salmon;font-size: 20px"
              ></span>
            </el-popover>
          </div>
        </div>
      </draggable>
      <draggable v-model="objData.content" :options="{group:'people'}" v-else>
        <div
          v-for="(stepCon, stepConIndex) in objData.content"
          :key="stepConIndex"
          style="margin: 20px 0;"
        >
          <div
            v-if="stepCon.type == 'text'"
            style="border:1px dotted #cccccc;border-radius: 4px;margin: 5px;position: relative;"
          >
            <div
              style="line-height: 2;padding-left: 5px"
              @click="pointTextClick(stepCon.val, stepConIndex)"
              v-html="replaceN(stepCon.val)"
            >
            </div>
            <el-popover
              trigger="click"
              placement="top"
              width="160"
              v-model="stepCon.IsDel"
              v-show="mainOption.operate === 'show'?false:true"
            >
              <p>确定删除内容吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="stepCon.IsDel = false">取消</el-button>
                <el-button type="primary" size="mini" @click="stepConDel(stepConIndex)">确定</el-button>
              </div>
              <span
                class="el-icon-error"
                slot="reference"
                style="position: absolute;top:0;right:0;color: salmon;font-size: 20px;transform: translateX(40%) translateY(-40%)"
              ></span>
            </el-popover>
          </div>
          <div v-else style="position: relative">
            <el-image
              :src="stepCon.imgList.url"
              @click="pointIMgClick(stepCon.imgList.url, stepConIndex)"
              lazy
            ></el-image>
            <el-popover
              placement="top"
              width="160"
              v-model="stepCon.IsDel"
              v-show="mainOption.operate === 'show'?false:true"
            >
              <p>确定删除内容吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="stepCon.IsDel = false">取消</el-button>
                <el-button type="primary" size="mini" @click="stepConDel(stepConIndex)">确定</el-button>
              </div>
              <span
                class="el-icon-error"
                slot="reference"
                style="position: absolute;top:0;right:0;color: salmon;font-size: 20px"
              ></span>
            </el-popover>
          </div>
        </div>
      </draggable>
    </div>
    <div
      class="btnGroup"
      style="display: flex;justify-content: flex-end;"
      v-show="mainOption.operate === 'show'?false:true"
    >
      <el-button size="mini" type="primary" @click="stepAddText">添加文本</el-button>
      <el-button size="mini" type="primary" @click="stepAddImg">添加图片</el-button>
    </div>
    <!-- 资源选择 :option-state="optionState" -->
    <div v-if="mainOption.tiOption.resources?true:false">
      <resource-comp
        :append-to-body="appendToBody"
        :server-data="pointInResourceData"
        :resource-comp-form="{resources: objData.resources}"
        ref="resourceComp"
        @transmit-change-arr="transmitChangeArr"
        @scroll-more="scrollMore"
        :point-resource-option="pointResourceOption"
        transmit-name="content"
        :day-index="dayIndex"
        :point-index="pointIndex"
        :main-option="mainOption"
      ></resource-comp>
    </div>

    <!-- 图片上传加载中 -->
    <!-- 全局text编辑 :transmit-val="transmitVal" -->
    <dialog-text-edit
      :add-text-state-num="addTextStateNum"
      :append-to-body="appendToBody"
      @text-edit-transmit="textEditTransmit"
      @text-edit-updata-transmit="textEditUpdataTransmit"
      :transmit-val="nowObj"
      :step-index="stepIndex"
      :is-updata="isUpdata"
      @text-edit-cancel-transmit="textEditCancelTransmit"
      ref="textedit"
      :main-option="mainOption"
    ></dialog-text-edit>
    <!-- 全局裁剪 -->
    <dialog-img-edit
      :is-img-updata="isImgUpdata"
      :append-to-body="appendToBody"
      :dialog-img-add-num="dialogImgAddNum"
      :Img-utils-title="ImgUtilsTitle"
      @img-url-transmit="imgUrlTransmit"
      ref="imgTextDialogImg"
      :cropper-option-data="dayCompCropperOption"
    ></dialog-img-edit>
  </div>
</template>
<script>
// window.location.protocol+"//"+window.location.host
function http(url, method, data) {
  return new Promise((res, rej) => {
    axios({
      url,
      method,
      data
    })
      .then(pos => res(pos))
      .catch(err => rej(err));
  });
}
module.exports = {
  name: "imgText",
  data() {
    return {
      // 资源数据拉取
      // serverData: [],
      // 当前传递的数据
      scenicDataComp: this.scenicData,
      nowObj: {
        val: ""
      },
      scenieContent: this.objData.content,
      // 是否修改文本
      isUpdata: false,
      // 是否修改图片
      isImgUpdata: false,
      // 当前的content的index
      stepIndex: 0,
      // 点击文字修改所传的值
      transmitVal: "",
      progressShow: false,
      // 上传图片进度
      progress: 0,
      visible: false,
      dataContent: [],
      dialogImgAddNum: 0,
      // 点击添加文本一直加的数
      addTextStateNum: 0,
      // 是否打开内层dialog
      appendToBody: true,
      pushPointState: false,
      ImgUtilsTitle: "选择图片",
      // 全局裁剪显示状态
      addImg: false,
      Form: this.objData,
      msg: "这是msg信息",
      clickMsg: "clickMsg",
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        playTime: [
          { required: true, message: "请输入游玩时长", trigger: "blur" }
        ]
      }
    };
  },
  components: {
    "dialog-text-edit": httpVueLoader("./dialogTextEdit.vue"),
    "dialog-img-edit": httpVueLoader("./dialogImgEdit.vue"),
    "resource-comp": httpVueLoader("./resourceComp.vue")
  },
  watch: {
    scenicData: {
      handler(now) {
        console.log("secnic data watch");
        // this.scenicDataComp = now;
        this.$set(this, 'scenicDataComp', now)
      }
    }
  },
  props: {
    pointResourceOption: {
      type: Object,
      default: () => {
        return {};
      }
    },
    scenicData: {
      type: Array,
      default: () => {
        return [];
      }
    },
    name: {
      type: String,
      default: ''
    },
    mainOption: {
      type: Object,
      default: () => {
        return {};
      }
    },
    pointInResourceData: {
      type: Array,
      default: () => {
        return [];
      }
    },
    dayCompCropperOption: {
      type: Object,
      default: () => {
        return {};
      }
    },
    objData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    dayIndex: {
      type: Number,
      default: 0
    },
    pointIndex: {
      type: Number,
      default: 0
    }
  },
  methods: {
    scrollMore(name) {
      this.$emit("scroll-more", name);
    },
    change(e) {
      this.$emit("change-data", this.scenicDataComp);
    },
    runPointForm() {
      let that = this;
      return allCheckRules(that, "dialogPointForm");
    },
    transmitChangeArr(arr) {
      // this.Form.optionState = arr;
      this.objData.resources = arr;
    },
    // 图文混排数据提交
    // TIConfirm() {
    //   const objdata = {
    //     title: "",
    //     play_time: null,
    //     content: [],
    //     resources: []
    //   };
    //   objdata.title = this.Form.title.val;
    //   objdata.play_time = this.Form.playTime.val;
    //   objdata.content = this.dataContent;
    //   objdata.resources = this.Form.optionState;
    //   this.formSubmit(objdata);
    // },
    runContentComp() {
      let arr = [];
      let that = this;
      arr.push(this.$refs.resourceComp.resourceCompSubmit());
      arr.push(allCheckRules(that, "dialogPointForm"));
      return arr;
    },
    // formSubmit(objdata) {
    //   let arr = [];
    //   let that = this;
    //   // 调用子组件的表单验证
    //   arr.push(this.$refs.resourceComp.resourceCompSubmit());
    //   arr.push(allCheckRules(that, "dialogPointForm"));
    //   Promise.all(arr)
    //     .then(() => {
    //       this.TICancel();
    //       this.$emit("transmit-imgtextdata", objdata);
    //     })
    //     .catch(err => {
    //       this.$message({ message: "请填写完整信息", type: "warning" });
    //       console.log("err");
    //     });
    // },
    // 图文混排取消
    TICancel() {
      this.Form.title.val = "";
      this.dataContent = [];
      this.Form.optionState = [];
      this.Form.playTime.val = 1;
      this.pushPointState = false;
      // this.$set(this.Form, "optionState", []);
    },
    // 取消
    textEditCancelTransmit() {
      this.isUpdata = false;
    },
    // 修改后的值和事件传递
    textEditUpdataTransmit(str) {
      if (this.name === "scenic") {
        this.scenicDataComp[this.stepIndex].val = str;
        this.isUpdata = false;
      } else {
        this.objData.content[this.stepIndex].val = str;
        this.isUpdata = false;
      }
    },
    imgUrlTransmit(imgurl, isImgUpdata) {
      // const obj = { url: imgurl, type: "img", IsDel: false };
      const obj = { imgList: { url: imgurl }, type: "img", IsDel: false };
      const that = this;
      if (this.name === "scenic") {
        if (isImgUpdata) {
          this.scenicDataComp[this.stepIndex].imgList.url = imgurl;
        } else {
          console.log(obj, "obj");
          this.scenicDataComp.push(obj);
        }
      } else {
        if (isImgUpdata) {
          this.objData.content[this.stepIndex].imgList.url = imgurl;
        } else {
          this.objData.content.push(obj);
        }
      }
    },
    replaceN(str) {
      if (str) {
        return str.replace(/\n/g, "<br>");
      }
    },
    // 添加text传来的
    textEditTransmit(str) {
      if (this.name === "scenic") {
        console.log("scenic");
        let obj = { val: "", type: "text", IsDel: false };
        obj.val = str;
        this.scenicData.push(obj);
      } else {
        let obj = { val: "", type: "text", IsDel: false };
        obj.val = str;
        this.objData.content.push(obj);
      }
      // console.log(this.dataContent)
    },
    stepAddImg() {
      console.log(this.$refs, "refs");
      this.isImgUpdata = false;
      this.$refs.imgTextDialogImg.$refs.myInput.value = "";
      this.$refs.imgTextDialogImg.$refs.myInput.click();
      this.ImgUtilsTitle = "添加图片";
      // this.addImg = true;
      // this.dialogImgAddNum++;
    },
    // 添加文本
    stepAddText() {
      // this.addTextStateNum++;
      this.$refs.textedit.addText = true;
    },
    pointIMgClick(url, stepConIndex) {
      if (this.mainOption.operate !== "show") {
        console.log(url, stepConIndex, "url, stepConIndex");
        this.stepIndex = stepConIndex;
        this.isImgUpdata = true;
        // this.$refs.imgTextDialogImg.cropperOptionData.img = url;
        this.dayCompCropperOption.img = url;
        this.ImgUtilsTitle = "裁剪图片";
        this.$refs.imgTextDialogImg.addImg = true;
      }
    },
    // 确认删除
    stepConDel(stepConIndex) {
      // this.dataContent.splice(stepConIndex, 1);

      if (this.name === "scenic") {
        this.scenicDataComp.splice(stepConIndex, 1);
      } else {
        this.objData.content.splice(stepConIndex, 1);
      }
    },
    // 取消
    stepConCancel(stepConIndex) {
      this.dataContent[stepConIndex].IsDel = false;
    },
    // 修改文本
    pointTextClick(val, stepConIndex) {
      if (this.mainOption.operate !== "show") {
        this.nowObj.val = val;
        this.isUpdata = true;
        this.$refs.textedit.addText = true;
        this.transmitVal = val;
        this.stepIndex = stepConIndex;
      }
    },
    handleDialogClose() {},
    divClick() {
      this.$emit("transmit-data", this.clickMsg);
    },
    uploadImgFn(imgUrl, Bucket, Region) {
      const that = this;
      return new Promise((res, rej) => {
        cos.sliceUploadFile(
          {
            Bucket,
            Region,
            Key: "images/" + new Date().getTime(),
            Body: imgUrl,
            onHashProgress: function(progressData) {
              console.log("校验中", JSON.stringify(progressData));
            },
            onProgress: function(progressData) {
              // , JSON.stringify(progressData)
              console.log("上传中", progressData.percent, progressData.speed);
              const progress =
                Math.round((progressData.loaded / progressData.total) * 10000) /
                100;
              that.progress = progress;
              var time;
              clearTimeout(time);
              time = setTimeout(() => {
                that.progressShow = false;
                that.progress = 0;
              }, 200);
              console.log(progress, "progress");
            }
          },
          (err, data) => {
            if (err) {
              rej(err);
            } else {
              res(data);
            }
          }
        );
      });
    }
  }
};
</script>
<style scoped>
.content {
  min-height: 400px;
}
.img-text {
  width: 100%;
  /* min-height: 300px; */
  border: 1px solid seagreen;
  padding: 10px;
  box-sizing: border-box;
}
.btn-group {
  margin-top: 30px;
}
#img-text .el-collapse-item__header {
  background-color: transparent;
}
#img-text .el-collapse-item__wrap {
  background-color: transparent;
}
</style>